#include "reactor_threadpool.hpp"
#include "my_task.hpp"
#include "packet.h"
#include <iostream>
#include <functional>

using std::cout;
using std::endl;

namespace rocket 
{

reactor_threadpool::reactor_threadpool(int port,string ip,int pool_capacity,int task_list_capacity)
:_server(port,ip)
,_pool(pool_capacity,task_list_capacity)
{

}

reactor_threadpool::~reactor_threadpool()
{

}

void reactor_threadpool::start()
{
    using namespace std::placeholders;
    
    set_callback(std::bind(&reactor_threadpool::new_link,this,_1),
    std::bind(&reactor_threadpool::old_link,this,_1),
    std::bind(&reactor_threadpool::close_link,this,_1));
    _pool.start();
    
    _server.turn_on();

}

void reactor_threadpool::stop()
{
    _server.turn_off();
    _pool.stop();
}

void reactor_threadpool::set_callback(function<void(shared_ptr<tcp_link>)>callback_new,
            function<void(shared_ptr<tcp_link>)>callback_old,
            function<void(shared_ptr<tcp_link>)>callback_close)
{
    _server.set_callback(callback_new,callback_old,callback_close);
}


void reactor_threadpool::new_link(shared_ptr<tcp_link>new_one)
{
    cout<<"new_link "<<new_one->get_link_line()<<endl;
}


void reactor_threadpool::old_link(shared_ptr<tcp_link>old_one)
{
    
//    string buff(1024,'\0');
//    int ret=old_one->receive(buff, buff.capacity());
    packet data;
    int ret=old_one->read_packet(data);
    data.print();
//    cout<<"receive "<<ret<<":"<<buff<<endl;
    
//    my_task *task=new my_task(old_one,buff);

    my_task task(old_one,data);

    function<void()>f=std::bind(&my_task::something,task);
    _pool.add_task(f);
}   


void reactor_threadpool::close_link(shared_ptr<tcp_link>close_one)
{
    cout<<"close_link "<<close_one->get_link_line()<<endl;
    
}



}//end of namespace rocket
